const env = require('./config.js');

const base64 = require('./base64.js');
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');

/*
 *上传文件到阿里云oss
 *@param - filePath :图片的本地资源路径
  @param - path :上传oss哪个路径下
 *@param - successc:成功回调
 *@param - failc:失败回调
 */
const uploadFile = function(filePath, path, suffix, successc, failc) {
	// console.log(suffix);
	if (!filePath || filePath.length < 9) {
		wx.showModal({
			title: '文件错误',
			content: '请重试',
			showCancel: false,
		})
		return;
	}
	//存放图片命名格式：自定义时间戳给图片名字(可以自己改)
	// const aliyunFileKey = path + new Date().getTime() + Math.floor(Math.random() * 150) + '.png';
	const aliyunFileKey = path + new Date().getTime() + Math.floor(Math.random() * 150) + suffix;

	const aliyunServerURL = env.uploadImageUrl; //OSS地址，https
	const accessid = env.OSSAccessKeyId;
	const policyBase64 = getPolicyBase64();
	const signature = getSignature(policyBase64);

	wx.uploadFile({
		url: aliyunServerURL, //开发者服务器 url
		filePath: filePath, //要上传文件资源的路径
		name: 'file', //必须填file
		formData: {
			'key': aliyunFileKey,
			'policy': policyBase64,
			'OSSAccessKeyId': accessid,
			'signature': signature,
			'success_action_status': '200',
			'callback': base64.encode(JSON.stringify(getBackdata())),
		},
		success: function(res) {
			// console.log(res, '所有的');
			if (res.statusCode != 200) {
				failc(new Error('上传错误:' + JSON.stringify(res)))
				return;
			}
			// 9.2 修改 成功后返回 url 和 id
			let fileinfo = {
				fileURL: aliyunServerURL + aliyunFileKey,
				fileId: JSON.parse(res.data).tempfileid
			}
			
			successc(fileinfo);
			// successc(aliyunServerURL + aliyunFileKey);
		},
		fail: function(err) {
			err.wxaddinfo = aliyunServerURL;
			failc(err);
		},
	})
}

const getPolicyBase64 = function() {
	let date = new Date();
	date.setHours(date.getHours() + env.timeout);
	let srcT = date.toISOString();
	const policyText = {
		"expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了 
		"conditions": [
			["content-length-range", 0, 100 * 1024 * 1024] // 设置上传文件的大小限制,5mb
		]
	};

	const policyBase64 = base64.encode(JSON.stringify(policyText));
	return policyBase64;
}

const getSignature = function(policyBase64) {
	const accesskey = env.AccessKeySecret;
	const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
		asBytes: true
	});
	const signature = Crypto.util.bytesToBase64(bytes);
	return signature;
}

const getBackdata = function() {
	const accesskey = env.AccessKeySecret;
	const callbackdata = {
		"callbackUrl": env.callbackUrl + env.query_string,
		"callbackBody": "bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&imageInfo.height=${imageInfo.height}&imageInfo.width=${imageInfo.width}&imageInfo.format=${imageInfo.format}&my_var=${x:my_var}",
		//"callbackBodyType": "application/json"
	};
	return callbackdata;
}

module.exports = uploadFile;
